package LeetCode.leetcode;

/**
 * 盛最多水的容器
 * @author: leiwenkang02@meituan.com
 * @date: 2018/9/19
 * @time: 20:04
 */
public class Test11盛最多水的容器 {
    public static void main(String[] args) {
        int[] height = {1, 8, 6, 2, 5, 4, 8, 3, 7};
        System.out.println(maxArea(height));
    }

    //O(n)
    public static int maxArea(int[] height) {
        if (height == null || height.length < 2) {
            return 0;
        }

        int left = 0;
        int right = height.length - 1;
        int maxArea = 0;
        while (left < right) {
            int area = Math.min(height[left], height[right]) * (right - left);
            if (area > maxArea) {
                maxArea = area;
            }
            if (height[left] < height[right]) {//每次保留较长的柱子，因为较短的柱子不再可能装比此情况更多的水了
                left++;
            } else {
                right--;
            }
        }
        return maxArea;
    }



    //O(n^2)
    public static int maxArea2(int[] height) {
        if (height == null || height.length < 2) {
            return 0;
        }
        int maxArea = 0;
        for (int i = 0; i < height.length - 1; i++) {
            for (int j = i + 1; j < height.length; j++) {
                int area = Math.multiplyExact((j - i), Math.min(height[i], height[j]));
                if (maxArea < area) {
                    maxArea = area;
                }
            }
        }
        return maxArea;
    }
}
